/*
 * 行车数据分析-旧版
 * */
require(['grid', 'topBar', 'highcharts', 'date', 'zTreeCheckbox'], function () {
    var $top = $('#top'),
        $fileList = $("#fileList"),
        isFirst = true,
        postData,
        editDialog,
        $dataChart,
        autoRefreshReq = null;

    //顶部栏初始化
    function topBarInit() {
        //顶部搜索栏
        $top.topBar({
            left: [
                {
                    type: 'filter',
                    search: function () {
                        search();
                    },
                    item: [
                        {
                            text: '时间段',
                            name1: 'beginTime',
                            name2: 'endTime',
                            format: 'yyyy-MM-dd HH:mm:ss',
                            type: 'dateLine'
                        }
                    ]
                }
            ],
            right: [
                {
                    text: '文件导出',
                    type: 'btn',
                    width: '698',
//                authority: '',
                    click: function () {
                        fileExport();
                    }
                },

                {
                    text: '文件下载',
                    type: 'btn',
                    width: '698',
//                authority: '',
                    click: function () {
                        fileUpLoad();
                    }
                }
            ]
        });
    }

    //grid初始化
    function gridInit() {
        function fileStFormat(value) {
            var val = '等待下载'; // 0
            switch (value) {
                case '1':
                    val = '下载中';
                    break;
                case '2':
                    val = '下载失败';
                    break;
                case '3':
                    val = '已下载';
                    break;
            }
            return val;
        }

        //暂时无用
        function genTimeFormat(value) {
            if (value) {
                return new Date(value).format('yyyy-MM-dd hh:mm:ss');
            } else {
                return "";
            }
        }

        $fileList.grid({
            url: "/loadFile/getLoadFileRcd.htm",
            height: "200",
            colModel: [
                {name: "rcrdId", index: "rcrdId", label: 'id', key: true, hidden: true},
                {name: "fileName", index: "fileName", label: '文件名', width: 150},
                {name: "fileSt", index: "fileSt", label: '文件状态', width: 80, formatter: fileStFormat},
                {name: "failInfo", index: "failInfo", label: '状态描述'},
                {name: "fileBeginTime", index: "fileBeginTime", label: '文件记录的开始时间', width: 110},
                {name: "fileEndTime", index: "fileEndTime", label: '文件记录的结束时间', width: 110}
            ],
            showPager: false,
            loadComplete: function (xhr) {
                if (isFirst) {
                    isFirst = false;
                } else {
                    if (xhr && xhr.msgType && xhr.msgType != "1" && xhr.msg) {
                        $.messager.alert("提示", xhr.msg, "info");
                    } else if (xhr && xhr.obj && $.isArray(xhr.obj) && xhr.obj.length > 0) {

                    } else {
                        $.messager.alert("提示", "当前时间区间没有相关数据。", "info");
                    }
                }
            }
        });

    }

    //封装请求参数
    //beginTime
    //endTime
    //carId/carIds
    //componentType
    function getPostData() {//orgIds,type,beginTime,endTime
        postData = $top.parent().getValues();
        postData.componentType = '01';
        postData.type = 'CAR';

        if (!postData.beginTime || !postData.endTime) {
            $.messager.alert("警告", "请先选择开始和结束时间，时间区间不能跨天", "info");
            return false;
        }

        if (postData.beginTime.substr(0, 10) != postData.endTime.substr(0, 10)) {
            $.messager.alert("警告", "时间区间不能跨天", "info");
            return false;
        }

        var nodes = commonFun.getLeftTreeSelectedNodes();
        if (nodes && nodes.length > 0) {
            postData.carId = nodes[0].id;
            postData.carIds = nodes[0].id;
            postData.orgIds = nodes[0].id;
            postData.carNo = nodes[0].cd;
            postData.funcId = "02";

            //console.log(postData);
            return true;
        } else {
            $.messager.alert("警告", "请先选择一辆车", "info");
            return false;
        }
    }

    var getfileList = function () {
        $fileList.grid('setGridParam', {
            datatype: "json",
            postData: postData
        }).trigger("reloadGrid");
    }

    //清除信息
    function clearGridData() {
        $fileList.grid('clearGridData');
    }

    function search() {
        if (getPostData()) {
            clearGridData();
            getfileList();
        }
    }

    //创建遮罩层
    /*function createLoadMask() {
     loadMask = commonFun.createLoadMask($('body'));
     }*/

    //清除遮罩层
    /*function clearLoadMask() {
     if (loadMask) {
     loadMask.remove();
     loadMask = null;
     }
     }*/

    //自动刷新各个文件的状态
    function autoRefresh() {
        var fileNames = [];
        var rowIds = $fileList.getGridParam().selarrrow;

        $.each(rowIds, function (index, item) {
            var row = $fileList.getRowData(item);
            if (row.fileSt != '已下载') {
                fileNames.push(row.fileName);
            }
        });

        if (autoRefreshReq) {//如果之前的请求还在，取消之前的请求
            autoRefreshReq.abort();
        }
        
        autoRefreshReq = $.ajax({
            type: "POST",
            url: $.getProjectName() + "/loadFile/getLoadFileSt.htm",
            data: {
                fileNames: fileNames.join(','),
                beginTime: postData.beginTime,
                endTime: postData.endTime,
                carIds: postData.carIds,
                componentType: postData.componentType
            },
            dataType: "json",
            success: function (data) {
                autoRefreshReq = null;
                if (data && data.obj) {
                    var complete = true;
                    $.each(data.obj, function (index, item) {
                        $fileList.setRowData(item.rcrdId, item);
                        if (item.fileSt == '0' || item.fileSt == '1') {
                            setTimeout(autoRefresh, 4000);
                            complete = false;
                        }
                        if (complete) {
                            // clearLoadMask();
                        }
                    })
                } else {
                    // clearLoadMask();
                }
            }
        });

        /*autoRefreshReq = $.ajaxExt({
            url: "/loadFile/getLoadFileSt.htm",
            data: {
                fileNames: fileNames.join(','),
                beginTime: postData.beginTime,
                endTime: postData.endTime,
                carIds: postData.carIds,
                componentType: postData.componentType
            }
        }).done(function (data) {
            autoRefreshReq = null;
            if ($.isArray(data)) {
                var complete = true;
                $.each(data, function (index, item) {
                    $fileList.setRowData(item.rcrdId, item);
                    if (item.fileSt == '0' || item.fileSt == '1') {
                        setTimeout(autoRefresh, 4000);
                        complete = false;
                    }
                    if (complete) {
                        //clearLoadMask();
                    }
                })
            } else {
                //clearLoadMask();
            }
        });*/
    }

    //文件下载
    function fileUpLoad() {
        if (postData) {
            var fileNames = [];
            var rowIds = $fileList.getGridParam().selarrrow;

            $.each(rowIds, function (index, item) {
                var row = $fileList.getRowData(item);
                if (row.fileSt != '已下载') {
                    fileNames.push(row.fileName);
                    
                    $fileList.setRowData(row.rcrdId, {'fileSt': '1'});
                }
            });

            if (fileNames.length == 0) {
                $.messager.alert("提示", "请选择等待下载的文件", "info");
                return;
            }

            $.ajaxExt({
                url: "/loadFile/getLoadFiles.htm",
                data: {
                    carIds: postData.carIds,
                    fileNames: fileNames.join(','),
                    ftpUrl: "ftp_engInfo_path",
                    componentType: postData.componentType
                }
            }).done(function () {
                //createLoadMask();
                autoRefresh();
            });
        } else {
            $.messager.alert("警告", "请先进行查询", "info");
        }
    }

    //文件导出
    //请选择已下载的文件进行导出
    function fileExport() {
        var rowIds = $fileList.getGridParam().selarrrow;
        var fileNames = [];
        var other = [];
        $.each(rowIds, function (index, item) {
            var row = $fileList.getRowData(item);
            if (row.fileSt == '已下载') {
                fileNames.push(row.fileName);
            } else {
                other.push(row.fileName);
            }
        });

        if (other.length == 0 && fileNames.length == 1) {
            //对文件进行分析
            var url = "/loadFile/getFtpFile.htm";
            $.exportFile(url, {fileNames: fileNames, ftpUrl: "ftp_engInfo_path"});
        } else {
            $.messager.alert("提示", "请选择 1个 已下载 的文件进行导出。", "info");
        }
    }

    //行车记录分析
    $(".chart_1").on('click', function () {
        if (postData && postData.carId && postData.beginTime && postData.endTime) {
            var option = {};
            option.title = '行车记录分析';
            getDrvRecordAnaDialog(option).dialog('exec', 'show', [postData]);
        } else {
            $.messager.alert("警告", "请先进行查询，下载要分析的文件", "info");
        }
    });

    /**
     * 获取表单对话框，如果没有就先创建
     * @param option {object} 对话框配置
     * @returns {jQuery}
     */
    function getDrvRecordAnaDialog(option) {
        option = option || {};
        if (editDialog) {
            editDialog.dialog('open');
            if (option.title) {
                editDialog.dialog('setOption', 'title', option.title);
            }
        } else {
            editDialog = $('<div>').dialog({
                title: option.title || '图表分析',
                url: './report/carAnalysis/carAnaRecordChart.htm',
                height: $(window.parent).height(),
                width: $(window.parent).width(),
                autoOpen: true,
                buttons: []
            });
        }
        return editDialog;
    }

    //外特性曲线图
    $(".chart_2").on('click', function () {
        dataChart('发动机-外特性曲线图');
    });

    //发动机功率图
    $(".chart_3").on('click', function () {
        dataChart('发动机-发动机功率图');
    });

    //电池-电压电流分析
    $(".chart_4").on('click', function () {
        dataChart('电池-电压电流分析');
    });

    //电池-续航里程分析
    $(".chart_5").on('click', function () {
        dataChart('电池-续航里程分析');
    });

    //电机-电压电流分析
    $(".chart_6").on('click', function () {
        dataChart('电机-电压电流分析');
    });

    //电机-车速转矩分析
    $(".chart_7").on('click', function () {
        dataChart('电机-车速转矩分析');
    });

    // 显示图表
    function dataChart(title) {
        if (postData
            && postData.orgIds
            && postData.type
            && postData.carId
            && postData.carNo
            && postData.beginTime
            && postData.endTime) {
            if (!$dataChart) {
                $dataChart = $('<div>').dialog({
                    url: './mainte/report/viewDataChart.htm',
                    height: 550,
                    width: 720,
                    buttons: [{
                        text: '关闭',
                        css: 'btn-cancel',
                        click: function () {
                            $(this).dialog('close');
                        }
                    }]
                });
            }

            if (title == '发动机-外特性曲线图') {
                $dataChart.dialog('exec', 'engineGraph', postData);//orgIds,type,beginTime,endTime
            } else if (title == '发动机-发动机功率图') {
                $dataChart.dialog('exec', 'enginePower', postData);//orgIds,type,beginTime,endTime
            } else if (title == '电池-电压电流分析') {
                $dataChart.dialog('exec', 'voltageAnaly', postData);//carId,beginTime,endTime
            } else if (title == '电池-续航里程分析') {
                $dataChart.dialog('exec', 'enduranceMile', postData);//carId,beginTime,endTime
            } else if (title == '电机-电压电流分析') {
                $dataChart.dialog('exec', 'vtgAndCrtRept', postData);//orgIds,type,beginTime,endTime,carNo
            } else if (title == '电机-车速转矩分析') {
                $dataChart.dialog('exec', 'spdAndTorqueRept', postData);//orgIds,type,beginTime,endTime,carNo
            }

            $dataChart.dialog('setOption', 'title', title);
            $dataChart.dialog('open');
        } else {
            $.messager.alert("警告", "请先进行查询，下载要分析的文件", "info");
        }
    }

    topBarInit();
    gridInit();
});